""" AssertTest. """
from common import *

# For serializing state data.
import base64
try:
   import cPickle as pickle
except:
   import pickle


default_data = [0,'state.data']

def setup(data = default_data):
    import wx
    dlg = wx.TextEntryDialog(
        None, 'Choose mode (0=Record, 1=Test, 2=Play)',
        'Configure AssertTest Process', str(data[0]))
    if dlg.ShowModal() == wx.ID_OK:
        data[0] = int(dlg.GetValue())
    dlg.Destroy()
    dlg = wx.TextEntryDialog(
        None, 'Enter state filename',
        'Configure AssertTest Process', str(data[1]))
    if dlg.ShowModal() == wx.ID_OK:
        data[1] = str(dlg.GetValue())
    dlg.Destroy()
    return data

def AssertTestFunc(in0,out0 , data = default_data):

    (mode, filename) = data

    if (mode == 0):
        f = open(filename, "wb")
    else:
        f = open(filename, "r")

    if (not f):
       print "AssertTest: Could not open state file!\n"
       return

    while True:

        # Read channel
        if (mode != 2):
           val = in0()

        # Record
        if (mode == 0):
            f.write(base64.b64encode(pickle.dumps(val)) + '\n')
            out0(val)

        # Test
        if (mode == 1):
            line = f.readline()
            if line == '':
                # Test done.
                out0(None)
            elif (val != pickle.loads(base64.b64decode(line[:-1]))):
                print "AssertTest: Error, value does not match!"
                print "Recorded value:"
                print pickle.loads(base64.b64decode(line[:-1]))
                print "Read value:"
                print val
            else:
                out0(val)

        # Play
        if (mode == 2):
            line = f.readline()
            if line == '':
               break
            
            out0(pickle.loads(base64.b64decode(line[:-1])))
            
    f.close()
